package com.mdd.common.utils;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.mdd.common.entity.order.Order;
import com.mdd.common.entity.refund.OrderRefund;
import com.mdd.common.mapper.order.OrderMapper;
import com.mdd.common.mapper.refund.OrderRefundMapper;
import org.apache.commons.lang3.RandomUtils;

/**
 * @ClassName SnUtils
 * @Description
 * @Autore Slien.zuo
 * @Date 2022/10/10 15:58
 * @Version 1.0
 **/
public class SnUtils {

    /**
     * @return java.lang.String
     * @Author slien
     * @Description 获取一个订单编号
     * @Date 14:23 2022/10/11
     * @Param []
     **/
    public static String getOrderSn() {
        while (true) {
            String date = TimeUtil.timestampToDate(System.currentTimeMillis() / 1000);
            String orderSn = date.replaceAll("\\D", "") + get6RandomCode();
            OrderMapper orderMapper = SpringUtil.getBean(OrderMapper.class);
            Order order = orderMapper.selectOne(
                    new QueryWrapper<Order>()
                            .select("id", "sn")
                            .eq("sn", orderSn).last("limit 1"));
            if (order == null) {
                return orderSn;
            }
        }

    }

    /**
     * @return java.lang.String
     * @Author slien
     * @Description 获取一个退款订单编号
     * @Date 14:23 2022/10/11
     * @Param []
     **/
    public static String getRefundOrderSn() {
        while (true) {
            String date = TimeUtil.timestampToDate(System.currentTimeMillis() / 1000);
            String refundNo = "R" + date.replaceAll("\\D", "") + get6RandomCode();
            OrderRefundMapper orderRefundMapper = SpringUtil.getBean(OrderRefundMapper.class);
            OrderRefund orderRefund = orderRefundMapper.selectOne(
                    new QueryWrapper<OrderRefund>()
                            .select("id", "sn")
                            .eq("sn", refundNo).last("limit 1"));
            if (orderRefund == null) {
                return refundNo;
            }
        }
    }

    /**
     * @return java.lang.String
     * @Author slien
     * @Description 获取6位的核销码
     * @Date 14:23 2022/10/11
     * @Param []
     **/
    public static String get6RandomCode() {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < 6; i++) {
            sb.append(RandomUtils.nextInt(0, 10));
        }
        return sb.toString();
    }

}
